import numeral from "numeral";

import { computed, ref } from "vue";

const baseWidth = 2300;

const clientWidth = ref(document.documentElement.clientWidth);

/**
 * 节流
 * @param {Function} fn
 * @param {Number} wait
 * @returns {Function}
 */
export function debounce(fn, wait) {
  let timeout = null;
  return function () {
    if (timeout !== null) {
      clearTimeout(timeout);
      timeout = null;
    }
    timeout = setTimeout(fn, wait);
  };
}

window.addEventListener(
  "resize",
  debounce(() => {
    console.log("ssss");
    clientWidth.value = document.documentElement.clientWidth;
  }, 200)
);

export const echartMapPx = (px) => {
  return computed(() => {
    return px * (clientWidth.value / baseWidth);
  });
};

/**
 * 用于判断一个值是否为空
 * @param {any} val
 * @returns {boolean}
 */
export const isEmpty = (val) => {
  return val === "" || val === void 0 || val === null;
};

/**
 * 格式化数据
 * @param {number} value 需要出来的数据
 * @param {string} format 采用哪种格式
 * @returns {string}
 */
export function numberFormat(value, format = "1,000") {
  if (isEmpty(value)) {
    return "";
  }
  return numeral(value).format(format);
}

/**
 * 获取指定范围的随机整数
 * @param {number} min - 小的值
 * @param {number} max - 大的值
 * @returns {number}
 */
export const getRandomInt = (min = 0, max = 1) => {
  return Math.floor(Math.random() * (max - min)) + min;
};

/**
 * 处理文本  指定长度换行
 * @param {string} label
 * @param {number} len
 * @returns
 */
export const disposeLabel = (label = "", len = 3) => {
  const portion = Math.ceil(label.length / len);
  const arr = [];
  for (let i = 0; i < portion; i++) {
    arr.push(label.slice(i * len, (i + 1) * len));
  }
  return arr.join("\n");
};
